package com.hkfrich.generator.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkfrich.common.controller.BaseController;
import com.hkfrich.common.utils.ConvertUtils;
import com.hkfrich.generator.domain.GenTableColumn;
import com.hkfrich.generator.utils.GenUtils;
import com.hkfrich.common.utils.ResultUtils;
import com.hkfrich.generator.domain.GenTable;
import com.hkfrich.generator.service.GenTableColumnService;
import com.hkfrich.generator.service.GenTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName GenTableController
 * @Desscription
 * @Author _HeiShuai
 * @Date 2022/8/27 10:18
 * @Version 1.0
 **/
@Controller
@RequestMapping(value = "/generator")
public class GeneratorController extends BaseController {

    @Autowired
    private GenTableService genTableService;
    @Autowired
    private GenTableColumnService genTableColumnService;


    /**
     * 查询gentable表
     *
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public ResultUtils selectGenTableList(@RequestBody GenTable genTable) {
        Page<GenTable> page = initBaseQueryPageWrapper(genTable);
        QueryWrapper<GenTable> query = initBaseQueryWrapper(genTable);
        Page<GenTable> pageGrid = genTableService.page(page, query);
        return ResultUtils.success(pageGrid, "获取genTable表信息成功");
    }



    /**
     * 查询数据库列表
     *
     * @return
     */
    @RequestMapping(value = "/dblist")
    @ResponseBody
    public ResultUtils selectDbTableList(@RequestBody GenTable genTable) {
        Page<GenTable> page = initBaseQueryPageWrapper(genTable);
        Page<GenTable> pageGrid = genTableService.selectDbTableList(page, genTable);
        return ResultUtils.success(pageGrid, "获取数据库表信息成功");
    }


    /**
     * 导入表结构（保存）
     *post 请求
     * @return
     */
    @RequestMapping(value = "/importTable")
    @ResponseBody
    public ResultUtils importTableSave(@RequestBody String paramsStr) {
        JSONObject params = getBodyParamsByStr(paramsStr);
        String[] tableNames = ConvertUtils.toStrArray(params.getString("tables"));
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        //初始化GenTable 写入库
        genTableService.importGenTable(tableList);
        return ResultUtils.success("添加成功");
    }


    /**
         * @Author _HeiShuai
         * @Description //预览代码
         * @Date 11:15 2022/9/2
         * @Param
         * @return
    **/
    @RequestMapping(value = "/preview")
    @ResponseBody
    public ResultUtils preview(@RequestBody String paramsStr) throws IOException
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        Map<String, String> dataMap = genTableService.previewCode(params.getLong("id"));
        return ResultUtils.success(dataMap,"预览数据获取成功");
    }

    /**
         * @Author _HeiShuai
         * @Description //生成表的代码文件
         * @Date 23:12 2022/8/30
         * @Param
         * @return get请求
    **/
    @RequestMapping(value = "/batchGenCode")
    @ResponseBody
    public void batchGenCode(HttpServletResponse response, @RequestParam(value = "tables") String tables) throws IOException {
        String[] tableNames = ConvertUtils.toStrArray(tables);
        byte[] bytes = genTableService.createGenTableFile(tableNames);
        GenUtils.writeZip(response,bytes);
    }

    /**
     * 批量删除代码生成业务
     */
    @RequestMapping("/removeByIds")
    @ResponseBody
    public ResultUtils removeByIds(@RequestBody String paramsStr)
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        String ids = params.getString("ids");
        List<Long> list = ConvertUtils.toList(ids);
        return ResultUtils.success(genTableService.removeOneGenTableAndGenTableColumns(list),"批量删除代码生成业务成功");
    }


    /**
     * 修改代码生成业务 获取表全部数据
     */
    @RequestMapping("/getInfoByTableId")
    @ResponseBody
    public ResultUtils getInfoByTableId(@RequestBody String paramsStr)
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        Long id = params.getLong("id");
        GenTable table = genTableService.selectGenTableById(id);
        List<GenTable> tables = genTableService.selectGenTableAll();
        LambdaQueryWrapper<GenTableColumn> query = new LambdaQueryWrapper<>();
        query.eq(GenTableColumn::getTableId,id);
        List<GenTableColumn> list = genTableColumnService.list(query);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return ResultUtils.success(map,"修改代码业务获取数据成功");
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping("/updateGenTable")
    @ResponseBody
    public ResultUtils editSave(@RequestBody String paramsStr)
    {
        GenTable genTable = JSONObject.parseObject(paramsStr, GenTable.class);
        JSONObject params = getBodyParamsByStr(paramsStr).getJSONObject("params");
        genTableService.validateEdit(genTable,params);
        genTableService.updateGenTable(genTable,params);
        return ResultUtils.success("修改成功");
    }


    /**
     * 同步数据库
     */
    @RequestMapping("/synchDb")
    @ResponseBody
    public ResultUtils synchDb(@RequestBody String paramsStr)
    {
        JSONObject params = getBodyParamsByStr(paramsStr);
        genTableService.synchDb(params.getString("tableName"));
        return ResultUtils.success("同步成功");
    }

}
